/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.spring.event.reactive;

import org.apache.commons.lang3.ObjectUtils;
import org.pajamas.starter.core.util.StreamOptUtils;
import org.pajamas.starter.integration.spring.event.AbstractPropertyChangedEventHandler;

import java.util.EventObject;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author william
 * @since 2024/3/29
 */
public abstract class FluxPropertyChangedEventHandler<P, K> extends AbstractPropertyChangedEventHandler {
    protected FluxPropertyChangedEventHandler(String propertyKey, boolean skipInitializing) {
        super(propertyKey, skipInitializing);
    }

    protected abstract Flux<P> getUnchangedProperty();

    protected abstract Flux<P> getChangedProperty();

    protected abstract K keyExtractor(P property);

    protected abstract Mono<Void> increase(Mono<P> mono);

    protected abstract Mono<Void> decrease(Mono<P> mono);

    protected void onSuccess() {
    }

    @Override
    public void handle(EventObject eventObject) {
        Flux<P> changedFlux = ObjectUtils.firstNonNull(this.getChangedProperty(), Flux.empty());
        Flux<P> unchangedFlux = ObjectUtils.firstNonNull(this.getUnchangedProperty(), Flux.empty());

        Mono<List<P>> changedMono = changedFlux.collectList();
        Mono<List<P>> unchangedMono = unchangedFlux.collectList();

        changedMono
                .zipWith(unchangedMono, (changedList, unchangedList) -> {
                    Set<P> increasing = StreamOptUtils.Filtering.difference(changedList, unchangedList,
                            this::keyExtractor);
                    Set<P> decreasing = StreamOptUtils.Filtering.difference(unchangedList, changedList,
                            this::keyExtractor);

                    return Flux.concat(Stream.of(
                            increasing.stream().map(Mono::justOrEmpty).map(this::increase),
                            decreasing.stream().map(Mono::justOrEmpty).map(this::decrease)
                    ).flatMap(stream -> stream).collect(Collectors.toList()));
                })
                .flatMapMany(flux -> flux)
                .then(Mono.fromRunnable(this::onSuccess))
                .subscribe();
    }
}
